package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.TimeUtil;
import com.xiaocz.common.widgets.load.LoadFactory;
import com.xiaocz.common.widgets.load.core.LoadManager;
import com.xiaocz.common.widgets.load.view.AbsView;
import com.xiaocz.common.widgets.recycler.RecyclerViewAdapter;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.adapter.VipTypeAdapter;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.interfaces.CancelUtils;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefresh;
import com.xiaocz.hblsubstitutedriving.model.PayReqEntity;
import com.xiaocz.hblsubstitutedriving.model.Rechargelist;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.model.VipModel;
import com.xiaocz.hblsubstitutedriving.utils.Constants;
import com.xiaocz.hblsubstitutedriving.widget.EmptyView;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;
import com.xiaocz.hblsubstitutedriving.widget.LoadingView;
import com.xiaocz.hblsubstitutedriving.wxapi.Wechat;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 购买会员
 *
 * @author xcz
 */
public class VipActivity extends BaseActivity implements RoundRefresh, VipTypeAdapter.onClickListener {

    @BindView(R.id.layout_base)
    NestedScrollView layoutBase;
    @BindView(R.id.iv_banner)
    AppCompatImageView iv_banner;
    @BindView(R.id.state_info)
    TextView state_info;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_vip_time)
    TextView tv_vip_time;
    @BindView(R.id.layout_vip)
    LinearLayout layout_vip;

    /**
     * DATA
     */
    private LoadManager mLoadManager;
    private VipTypeAdapter vipTypeAdapter;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_vip;
    }

    public static void show(Context context) {
        Intent intent = new Intent(context, VipActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        mLoadManager = LoadFactory.getInstance().register(layoutBase, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                webRechargeList();
            }
        });
    }

    @BindView(R.id.layout_model)
    RelativeLayout layout_model;
    @BindView(R.id.tv_this_ad)
    TextView tv_this_ad;
    @BindView(R.id.tv_this_vip)
    TextView tv_this_vip;

    @Override
    protected void initData() {
        super.initData();
        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        vipTypeAdapter = new VipTypeAdapter(new RecyclerViewAdapter.AdapterListenerImpl<Rechargelist>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<Rechargelist> holder, Rechargelist data, int position) {
                super.onItemClick(holder, data);
                for (Rechargelist type : vipTypeAdapter.getDataList()) {
                    type.setState(false);
                }
                vipTypeAdapter.getDataList().get(position).setState(true);
                vipTypeAdapter.notifyDataSetChanged();// 刷新显示
                onDialog(data);
            }
        });
        vipTypeAdapter.vipTypeAdapter(this);

        mRecyclerView.setAdapter(vipTypeAdapter);
        CancelUtils.setWxPayRefresh(this);
        webRechargeList();
    }

    private void onDialog(final Rechargelist data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage(thisVipModel.getText());
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!App.mWxApi.isWXAppInstalled()) {
                    App.getInstance().showMessage("您还未安装微信客户端");
                    return;
                }
                webPay(data.getId());
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


    @OnClick({R.id.tv_bz, R.id.state_info})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_bz:
                if (Constants.getLocation() != null) {
                    WebViewActivity.show(mContext, Common.Constant.API_H5 + "apph5/deductionStandard?city=" + Constants.getLocation().getCity());
                } else {
                    App.getInstance().showMessage(getResources().getString(R.string.none_location));
                }
                break;
            case R.id.state_info:
                WebViewActivity.show(mContext, Common.Constant.API_H5 + "apph5/insuranceexplain");
                break;
        }
    }

    @Override
    public void onClickButton(int value, int position, Rechargelist data) {
        switch (value) {
            case 0:
                //dialogHint(data.getId());
                break;
            case 1:
                if (!App.mWxApi.isWXAppInstalled()) {
                    App.getInstance().showMessage("您还未安装微信客户端");
                    return;
                }
                break;
        }
    }

    /**
     * 提示并刷新
     */
    private void dialogTS() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage("会员资格已开启！");
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                webGetUserInfo();
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 获取充值列表
     */
    private void webRechargeList() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/getDriverRechargeList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<VipModel>>() {
                }.getType();
                RspModel<VipModel> rspModel = getAnalysisBase(mLoadManager, response, type, "获取充值列表");
                if (rspModel == null) {
                    return;
                }
                if (rspModel.getCode() == 200) {
                    if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                        vipTypeAdapter.replace(rspModel.getData().getRechargelist());
                        thisVipModel = rspModel.getData();
                        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
                        showView(info);
                    } else {
                        mLoadManager.showStateView(EmptyView.class);
                    }
                } else {
                    App.getInstance().showMessage(rspModel.getMessage());
                }
            }
        });
    }

    @BindView(R.id.tv_wx_ts)
    TextView tv_wx_ts;
    private VipModel thisVipModel;

    private void showView(UserInfo info) {
        Glide.with(mContext)
                .load(thisVipModel.getImg()).apply(Constants.getOptionsOthers())
                .into(iv_banner);
        SimpleDateFormat dateFormat = new SimpleDateFormat(Common.DateType.dateIF, Locale.CHINA);
        try {
            if (info.getExpiretime() == null || "".equals(info.getExpiretime()) ||
                    dateFormat.parse(info.getExpiretime()).getTime() / 1000L < TimeUtil.getLongStamp()) {//已到期或未开通
                tv_vip_time.setText("尚未开通，开通后每单将不扣信息费");
                tv_this_ad.setVisibility(View.VISIBLE);
                tv_this_vip.setVisibility(View.GONE);
                switch (thisVipModel.getOrderPattern()) {
                    case 1://按单提成
                        layout_vip.setVisibility(View.GONE);
                        layout_model.setVisibility(View.VISIBLE);
                        break;
                    case 2://包月模式
                        layout_vip.setVisibility(View.VISIBLE);
                        layout_model.setVisibility(View.GONE);
                        break;
                    case 3://混合模式
                        layout_vip.setVisibility(View.VISIBLE);
                        layout_model.setVisibility(View.VISIBLE);
                        break;
                }
            } else {//会员还未到期
                tv_vip_time.setText(String.format("%s到期", info.getExpiretime()));
                tv_this_ad.setVisibility(View.GONE);
                tv_this_vip.setVisibility(View.VISIBLE);
                switch (thisVipModel.getOrderPattern()) {
                    case 1://按单提成
                        layout_vip.setVisibility(View.GONE);
                        layout_model.setVisibility(View.VISIBLE);
                        break;
                    case 2://包月模式
                        layout_vip.setVisibility(View.VISIBLE);
                        layout_model.setVisibility(View.GONE);
                        break;
                    case 3://混合模式
                        layout_vip.setVisibility(View.VISIBLE);
                        layout_model.setVisibility(View.VISIBLE);
                        break;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        tv_wx_ts.setText(thisVipModel.getDetail());
    }

    /**
     * 获取微信支付参数
     */
    private void webPay(int vipId) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("driverRechargeConfig_id", vipId);
        asyncHttpPostFormData.addFormData("rechargeType", "1");//1-直接支付 2-平台预借 3-预借完成
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/createDriverRechargeOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<PayReqEntity>>() {
                }.getType();
                RspModel<PayReqEntity> rspModel = getAnalysis(response, type, "生成支付信息");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            Wechat.pay(rspModel.getData());
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 设置vip充值类型
     */
    private void webPayType(int vipId) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("driverRechargeConfig_id", vipId);
        asyncHttpPostFormData.addFormData("rechargeType", "2");//1-直接支付 2-平台预借 3-预借完成
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/createDriverRechargeOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "设置vip充值类型");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            dialogTS();
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 获取用户信息
     */
    private void webGetUserInfo() {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
//        asyncHttpPostFormData.addFormData("driver_id","2170");
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/getDriverinfo", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<UserInfo>>() {
                }.getType();
                RspModel<UserInfo> rspModel = getAnalysis(response, type, "获取用户信息");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null && !"".equals(rspModel.getData().toString())) {//保存用户
                            AccountManagers.login(rspModel.getData().getId(), rspModel.getData().getPhone(), new Gson().toJson(rspModel.getData()));
                            showView(rspModel.getData());
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    @Override
    public void onRoundRefresh(int type, String message) {
        if (type == 1) {
            App.getInstance().showMessage("成功");
            webGetUserInfo();
        }
    }
}
